<?php
namespace app\Services\admin;

use yii;
use app\commands\LibUtil;
use app\models\Ivtcode;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use yii\data\Pagination;
use app\Services\ApiService;

class LoginService extends ApiService
{
    /**
     * @return Service_Pay
     */
    public static function getInstance()
    {
        return parent::getInstance();
    }

    /**
     * 登录
     */
    public function login($arr){
        if ($arr['username']=='admin' && $arr['password']==Yii::$app->params['admin_pwd']){
            #生成token
            $token = $this->createToken(['username'=>$arr['username'],'password'=>$arr['password']]);
            return ['code'=>200,'message'=>'登录成功','data'=>['token'=>$token]];
        }else{
            return ['code'=>-1,'message'=>'用户名或者密码错误'];
        }
    }

    /**
     * 用户生成token
     */
    public function createToken($user){
        $signer = new Sha256();//使用Sha256加密，常用加密方式有Sha256,Sha384,Sha512
        $time = time();
        $tokenBuilder = (new Builder())
            ->issuedBy(Yii::$app->params['host'])// 设置发行人
            ->permittedFor(isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '')// 设置接收
            ->identifiedBy(Yii::$app->security->generateRandomString(10), true)// 设置id
            ->issuedAt($time)// 设置生成token的时间
            ->canOnlyBeUsedAfter($time+12*60)   // 设置token使用时间(实时使用)
            ->expiresAt($time + 60*60*12);      //设置token过期时间
        unset($user['password']);
        $tokenBuilder->withClaim('user', $user);
        $tokenBuilder->withClaim('login', '登录');
        //使用Sha256加密生成token对象，该对象的字符串形式为一个JWT字符串
        $token = $tokenBuilder->getToken($signer, new Key('jwt_secret'));
        return (string) $token;
    }

    /**
     * 用户列表 (默认普通用户) 1=普通用户 2=记者  3=VIP
     */
    public function getUserList($req){
        $limit = !empty($req['num'])?$req['num']:2;
        $offset = !empty($req['page'])?($req['page']-1)*$limit:0;
        $level = !empty($req['level'])?$req['level']:1;
        $where = ['Level'=>$level];
        if (!empty($req['Level'])){
            $where['Level'] = $req['Level'];
        }
        # 姓名 公司 手机号 邮箱 帐号
        if (!empty($req['name'])){
            $where['name'] = $req['name'];
        }
        if (!empty($req['Company'])){
            $where['Company'] = $req['Company'];
        }
        if (!empty($req['Cellphone'])){
            $where['Cellphone'] = $req['Cellphone'];
        }
        if (!empty($req['Username'])){
            $where['Username'] = $req['Username'];
        }
        if (!empty($req['email'])){
            $where['email'] = $req['email'];
        }
        $model = User::find()
            ->select('ID,Username,IDcard,Cellphone,Company,email,Position,Activity')
            ->where($where);
        $totalCount  = $model->count();
        if (!$totalCount){
            return ['code'=>-1,'message'=>'暂无数据'];
        }
        $pages = new Pagination(['totalCount' => $model->count()]);
        $list = $model->offset($offset)
            ->limit($limit)
            ->asArray()
            ->all();
        if (empty($list)){
            return ['code'=>-1,'message'=>'暂无数据'];
        }
        return ['code'=>200,'data'=>['list'=>$list,'totalCount'=>$totalCount]];
    }


    /**
     * 用户详情
     */
    public function getUserInfo($userID){
        $info = User::find()
            ->select('ID, Username, Nickname,  Company,  Position,  Cellphone,  Name,  IDcard,  CountryID,email,  Activity,  Regist,  Level')
            ->where(['ID'=>$userID])
            ->asArray()
            ->one();
        if (empty($info)){
            return ['code'=>-1,'message'=>'暂无数据'] ;
        }
        return ['code'=>200,'data'=>$info] ;
    }


    /**
     * 保存用户信息
     */
    public function saveUserInfo($req){
        $time = date("Y-m-d H:i:s",time());
        $info = [
            'Username' => $req['Username'],
            'Password' => $req['Password'],
            'Name'     => $req['Name'],
            'Nickname' => !empty($req['Nickname'])?$req['Nickname']:null,
            'Company'  => !empty($req['Company'])?$req['Company']:null,
            'Position' => !empty($req['Position'])?$req['Position']:null,
            'Cellphone'=> !empty($req['Cellphone'])?$req['Cellphone']:null,
            'email'    => !empty($req['email'])?$req['email']:null,
            'IDcard'   => !empty($req['IDcard'])?$req['IDcard']:null,
            'CountryID'=> !empty($req['CountryID'])?$req['CountryID']:null,
            'Activity' => !empty($req['Activity'])?$req['Activity']:1,
            'Level'    => !empty($req['Level'])?$req['Level']:1,
            'updatetime' => $time,
        ];
        if (!empty($req['userID'])){
            $count = User::find()
                ->where(['ID'=>$req['userID']])
                ->count();
            if (!$count){
                return ['code'=>-1,'message'=>'没有该用户'] ;
            }
            # update
            $res = Yii::$app->db->createCommand()->update('`user.user`',$info , ['ID'=>$req['userID']])->execute();
        }else{
            $info['Regist'] = $time;
            $res = Yii::$app->db->createCommand()->insert('`user.user`',$info )->execute();
        }
        if ($res){
            return ['code'=>200,'message'=>'保存成功'];
        }
        return ['code'=>-1,'message'=>'保存失败，请稍后重试'];
    }


    /**
     *  解封/封禁用户
     *
     */
    public function activeUser($req){
        $info = User::find()
            ->where(['ID'=>$req['userID']])
            ->count();
        if (empty($info)){
            return ['code'=>-1,'message'=>'没有该用户'] ;
        }
        $update = [
            'updatetime' => date("Y-m-d H:i:s",time()),
            'Activity'   => intval($req['Activity'])
        ];
        $res = Yii::$app->db->createCommand()->update('`user.user`' ,$update, ['ID'=> intval($req['userID'])])->execute();
        if ($res){
            return ['code'=>200,'message'=>'操作成功'];
        }
        return ['code'=>-1,'message'=>'操作失败，请稍后重试'];
    }

}